<?php
/***************************************************************************
 *   Copyright (C) 2008 by Julian Cromarty                                 *
 *   julian.cromarty@gmail.com                                             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

/**
 * A class to manage logins and sessions for the blog.
 *
 * This class provides functions to add users as well as authenticate
 * existing users and manage their sessions.
 *
 * @author Julian Cromarty
 */
class Session	{
/**
 * Class variable to store the database object
 */
	private $db;
		
/**
 * The constructor.
 *
 * Gets a connection to the database and stores it in the class
 */
	function __construct()	{
		session_name("ehwotay");
		session_set_cookie_params(600);
		session_start();
		if (!isset($_SESSION['db']))	{
			$this->db = new db();
			$this->db->connect();
			$_SESSION['db'] = $this->db;
		}
	}

/**
 * The destructor
 *
 * Destroys the connection to the database to clean up
 */
	function __destruct()	{
		//$this->db->close_connection();
		$this->db = null;
		session_write_close();
		//session_destroy();
	}

/**
 *
 * Log in to the application
 *
 * @param $usr Username
 * @param $pass Password
 * @param $rememberMe If true, save session in a cookie, else clear session as normal at the end. Unused atm..
 * @return 0 if successful, 1 otherwise
 */
	function login($usr, $pass, $rememberMe)	{
		$this->db = $_SESSION['db']->getInstance();
		$stmt = $this->db->prepare("SELECT author_id FROM authors WHERE author_name=?");
		$stmt->bind_param('s', $this->db->real_escape_string($usr));
		$stmt->execute();
		if (!$stmt->affected_rows > 0)	{	//Username not found. Return unsuccessful
			echo "Incorrect username or password";
			return 1;
		}
		$stmt->bind_result($aId);
		$stmt->fetch();
		$stmt->close();
		$stmt = $this->db->prepare("SELECT author_pass FROM authors WHERE author_id=?");
		$stmt->bind_param('i', $aId);
		$stmt->execute();
		if (!$stmt->affected_rows > 0)	{	//User ID not found. Return unsuccessful
			return 1;
		}
		$stmt->bind_result($aPassHash);
		$stmt->fetch();
		if (strcmp(sha1($pass), $aPassHash) != 0)	{	//Password hashes don't match
			echo "Incorrect username or password";
			return 1;
		}
		$stmt->close();
		$stmt = $this->db->prepare("SELECT author_email, author_level FROM authors WHERE author_id=?");
		$stmt->bind_param("i", $aId);
		$stmt->execute();
		$stmt->bind_result($aEmail, $aLevel);
		$stmt->fetch();
		$_SESSION['user_id'] = $aId;
		$_SESSION['username'] = $usr;
		$_SESSION['email'] = $aEmail;
		$_SESSION['auth_level'] = $aLevel;
		$stmt->close();
		return 0;
	}


/**
 * Checks user permissions
 * 
 * Makes sure that the user has permission to do whatever they are trying to do
 *
 * @param $required_levl The level to check against
 * @return 0 if allowed, 1 otherwise
 */
	function checkPermissions($required_level)	{
		if ((!isset($_SESSION['userID'])) && ($required_level <= 2))	{
			return 1;	//Not logged in and priveliges required
		}
		if ($_SESSION['auth_level'] <= $required_level)	{	//Lower level numerically = higer privs
			return 0;
		}
		else	{
			return 1;
		}
	}

/**
 * Adds a user to the database.
 *
 * @param $vars Array containing the data to put in the table
 * @return 0 on success, 1 otherwise
 */
	function addUser($vars)	{
		$con = $this->db->getInstance();
		if (!checkAuthLevel(getPriv(),$vars['author_level']))	{
			return 1;
		}
		$stmt = $con->prepare("INSERT INTO authors (author_name, author_email, author_level, author_pass) VALUES (?, ?, ?, SHA1(?))");
		$stmt->bind_param('ssis', $con->real_escape_string($vars['aName']), $con->real_escape_string($vars['aEmail']), $vars['author_level'], $con->real_escape_string($vars['aPass']));
		$stmt->execute();
		if ($stmt->affected_rows > 0)	{
			echo("success\n");
			return 0;
		}
		else	{
			echo "fail: ", __CLASS__, "::", __FUNCTION__, "\n";
			echo $stmt->error, "\n";
			$stmt->close();
			return 1;
		}
	}
}
?>
